﻿Imports Telerik.Web.UI
Imports System.Data.SqlClient
Imports System.Data

Partial Class PaymentVoucherDtl
    Inherits System.Web.UI.Page

    Dim _CommandName As String
    Dim _Command As String
    Dim Grid As RadGrid
    Dim PaymentVoucherHdrObj As New DBPaymentVoucherHdrSP
    Dim PaymentVoucherHdrDS As New Data.DataSet
    Dim PaymentVoucherDtlObj As New DBPaymentVoucherDtlSP
    Dim PaymentVoucherDtlDS As New Data.DataSet
    Dim AccountObj As New AccountsSP
    Dim AccountDataSet As New DataSet
    Dim ChequeObj As New DBChequeSP
    Dim ChequeDataSet As New DataSet
    Dim BankObj As New DBBankSP
    Dim BankDataSet As New DataSet
    Dim DeductionObj As New DBDeductionSP
    Dim DeductionDataSet As New DataSet
    Dim FilesObj As New DBtblFilesSP
    Dim FilesDatatset As New Data.DataSet
    Public strConnection As String = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ConnectionString.ToString

    Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Me.Theme = GetGlobalResourceObject("SystemResource", "Theme")
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Dim _lblPageTitle As Label
            _lblPageTitle = Me.Master.FindControl("lblPageTitle")
            _lblPageTitle.Text = GetLocalResourceObject("PageTitle")
            hdnPaymentVoucherID.Value = Request.QueryString("PVID").ToString
            If hdnPaymentVoucherID.Value <> "" Then
                FillVoucherDtl()
                FillCheque()
            Else
                hdnPaymentVoucherID.Value = "-1"
                rdpPaymentVoucherDate.DbSelectedDate = Now    'Default Document Date is Today
                rtbYear.Text = Year(Now()).ToString()         'Default Year is the Current Year
            End If


            ' 'rbtnCancel.Attributes.Add("onClick", "javascript:history.back(); return false;")
        End If
    End Sub

    Protected Sub rgDeduction_ItemCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles rgDeduction.ItemCommand
        _CommandName = e.CommandName
    End Sub

    Protected Sub rgDeduction_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs) Handles rgDeduction.ItemDataBound
        If (TypeOf e.Item Is GridEditFormItem AndAlso e.Item.IsInEditMode) And _CommandName <> "InitInsert" Then
            Dim editFormItem As GridEditFormItem = CType(e.Item, GridEditFormItem)
            Dim parentItem As GridDataItem = editFormItem.ParentItem
            Dim box As RadComboBox = CType(editFormItem.FindControl("WUCAcc").FindControl("rcbv"), RadComboBox)
            box.SelectedValue = parentItem("AccountNo").Text
            Dim box1 As RadComboBox = CType(editFormItem.FindControl("WUCAcc").FindControl("rcbd"), RadComboBox)
            box1.SelectedValue = parentItem("AccountNo").Text
        End If
    End Sub

    Protected Sub rgPaymentVoucherDtl_ItemCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles rgPaymentVoucherDtl.ItemCommand
        _CommandName = e.CommandName
    End Sub

    Sub SaveControls()
        hdnPaymentVoucherID.Value = PaymentVoucherHdrObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.ExecuteScalar, "SavePaymentVoucherHdr", _
                                                      hdnPaymentVoucherID.Value, rtbYear.Text, rtbPaymentVoucherNo.Text, rdpPaymentVoucherDate.DbSelectedDate, rcbMainCostCenter.SelectedValue, rcbCostCenter.SelectedValue, _
                                                      rcbPaidforAccountNo.SelectedValue, rtbRemarks.Text, , Session("UserName").ToString(), Now)
        SaveDtl()
        SaveDeduction()

        hdnChequeID.Value = ChequeObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.ExecuteScalar, "SaveCheque", _
                                                      hdnChequeID.Value, hdnPaymentVoucherID.Value, , , , rtbChequeNo.Text, _
                                                      rdpChequeDate.DbSelectedDate, rntbChequeAmount.Text, rtbBeneficiaryName.Text, rtbBeneficiaryAccountNo.Text, rtbBeneficiaryBankName.Text)

        UploadAttachments()
    End Sub


    Protected Sub SaveDtl()
        For counter = 0 To rgPaymentVoucherDtl.Items.Count - 1
            PaymentVoucherDtlObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.ExecuteNonQuery, "SavePaymentVoucherDtl", rgPaymentVoucherDtl.Items(counter)("PaymentVoucherDtlID").Text, _
            hdnPaymentVoucherID.Value, _
            IIf(rgPaymentVoucherDtl.Items(counter)("Year").Text = "&nbsp;", "", rgPaymentVoucherDtl.Items(counter)("Year").Text), _
            IIf(rgPaymentVoucherDtl.Items(counter)("PayOrdID").Text = "&nbsp;", "", rgPaymentVoucherDtl.Items(counter)("PayOrdID").Text), _
             IIf(rgPaymentVoucherDtl.Items(counter)("AccountNo").Text = "&nbsp;", "", rgPaymentVoucherDtl.Items(counter)("AccountNo").Text), _
                 IIf(rgPaymentVoucherDtl.Items(counter)("ProgramNo").Text = "&nbsp;", "", rgPaymentVoucherDtl.Items(counter)("ProgramNo").Text), _
                 IIf(rgPaymentVoucherDtl.Items(counter)("ProjectNo").Text = "&nbsp;", "", rgPaymentVoucherDtl.Items(counter)("ProjectNo").Text), _
             IIf(rgPaymentVoucherDtl.Items(counter)("Amount").Text = "&nbsp;", "", rgPaymentVoucherDtl.Items(counter)("Amount").Text), _
             IIf(rgPaymentVoucherDtl.Items(counter)("Remarks").Text = "&nbsp;", "", rgPaymentVoucherDtl.Items(counter)("Remarks").Text))
        Next
    End Sub

    Protected Sub SaveDeduction()
        For counter = 0 To rgDeduction.Items.Count - 1
            DeductionObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.ExecuteNonQuery, "SaveDeduction", rgDeduction.Items(counter)("DeductionID").Text, _
            hdnPaymentVoucherID.Value, _
            IIf(rgDeduction.Items(counter)("Year").Text = "&nbsp;", "", rgDeduction.Items(counter)("Year").Text), _
               IIf(rgDeduction.Items(counter)("AccountNo").Text = "&nbsp;", "", rgDeduction.Items(counter)("AccountNo").Text), _
               IIf(rgDeduction.Items(counter)("ProgramNo").Text = "&nbsp;", "", rgDeduction.Items(counter)("ProgramNo").Text), _
               IIf(rgDeduction.Items(counter)("ProjectNo").Text = "&nbsp;", "", rgDeduction.Items(counter)("ProjectNo").Text), _
             IIf(rgDeduction.Items(counter)("Amount").Text = "&nbsp;", "", rgDeduction.Items(counter)("Amount").Text), _
             IIf(rgDeduction.Items(counter)("Remarks").Text = "&nbsp;", "", rgDeduction.Items(counter)("Remarks").Text))
        Next
    End Sub


#Region "Attachments"


    Private Sub UploadAttachments()

        Dim FileUpload As RadAsyncUpload = AsyncUploadVoucher

        lblUploadError.Visible = False
        If Not (FileUpload.UploadedFiles.Count > 0) Then
            'CType(Form.FindControl("lblUploadError"), Label).Visible = False
            'lblUploadError.Visible = False
            Return
        End If

        For i As Integer = 0 To FileUpload.UploadedFiles.Count - 1


            Dim fs As System.IO.Stream = FileUpload.UploadedFiles(i).InputStream

            Dim imageBytes As [Byte]() = New [Byte](fs.Length - 1) {}
            fs.Read(imageBytes, 0, CInt(fs.Length))
            fs.Close()



            'FilesDatatset = FilesObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.FillDataset, "RtvFile", , , CType(Form.FindControl("hdnVoucherID"), HiddenField).Value.ToString(), , , )
            Dim strQuery As [String]

            'If FilesDatatset.Tables(0).Rows.Count > 0 Then
            'insert the file into database
            'FilesDatatset = FilesObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.FillDataset, "SaveFile", , , , , , )
            'strQuery = "Update tblFiles set [Name] = @Name, [ContentType] = @ContentType , [Data] = @Data where [Voucher_IDC] = @Voucher_IDC and [Voucher_IDN] = @Voucher_IDN "
            'Else
            'insert the file into database
            strQuery = "insert into tblFiles([Voucher_IDC], [Voucher_IDN],[Name], [ContentType], [Data]) values (@Voucher_IDC, @Voucher_IDN,@Name, @ContentType, @Data)"
            'End If


            Dim cmd As New SqlCommand(strQuery)
            cmd.Parameters.AddWithValue("@Voucher_IDC", "PV")
            cmd.Parameters.AddWithValue("@Voucher_IDN", hdnPaymentVoucherID.Value.ToString())
            cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = FileUpload.UploadedFiles(i).GetName()

            'Make sure we are dealing with a Compatible File Format Like JPG or GIF file
            Dim extension As String = System.IO.Path.GetExtension(FileUpload.UploadedFiles(i).GetName()).ToLower()
            Dim MIMEType As String = Nothing
            Select Case extension
                Case ".gif"
                    MIMEType = "image/gif"
                    Exit Select
                Case ".jpg", ".jpeg", ".jpe"
                    MIMEType = "image/jpeg"
                    Exit Select
                Case ".png"
                    MIMEType = "image/png"
                    Exit Select
                Case ".bmp"
                    MIMEType = "image/bmp"
                    Exit Select
                Case ".txt"
                    MIMEType = "application/txt"
                    Exit Select
                Case ".pdf"
                    MIMEType = "application/pdf"
                    Exit Select
                Case ".doc"
                    MIMEType = "application/msword"
                    Exit Select
                Case ".xls"
                    MIMEType = "application/msexcel"
                    Exit Select
                Case ".docx"
                    MIMEType = "application/vnd.ms-word"
                    Exit Select
                Case ".xlsx"
                    MIMEType = "application/vnd.ms-excel"
                    Exit Select
                Case Else
                    '   Invalid file type uploaded
                    'CType(Form.FindControl("lblUploadError"), Label).Visible = True
                    lblUploadError.Visible = True
                    Return
            End Select

            cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = MIMEType
            cmd.Parameters.Add("@Data", SqlDbType.VarBinary).Value = imageBytes
            ' bytes;
            InsertUpdateData(cmd)

        Next

    End Sub

    Private Function InsertUpdateData(ByVal cmd As SqlCommand) As [Boolean]
        Dim con As New SqlConnection(strConnection)
        cmd.CommandType = CommandType.Text
        cmd.Connection = con
        Try
            con.Open()
            cmd.ExecuteNonQuery()
            Return True
        Catch ex As Exception
            Response.Write(ex.Message)
            Return False
        Finally
            con.Close()
            con.Dispose()
        End Try
    End Function


#End Region

    Sub DeleteRecord()
        PaymentVoucherHdrDS = PaymentVoucherHdrObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.FillDataset, "DeletePaymentVoucherHdr", hdnPaymentVoucherID.Value)
    End Sub

    Protected Sub FillCheque()
        ChequeDataSet = ChequeObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.FillDataset, "RtvCheque", , hdnPaymentVoucherID.Value)
        If ChequeDataSet IsNot Nothing Then


            If ChequeDataSet.Tables.Count > 0 Then
                If ChequeDataSet.Tables(0).Rows.Count > 0 Then

                    hdnChequeID.Value = ChequeDataSet.Tables(0).Rows(0).Item("ID").ToString()
                    WUCBank.DataBind()
                    WUCBank.SelectedValue = ChequeDataSet.Tables(0).Rows(0).Item("BankID").ToString()
                    WUCBankAccountNo.DataBind()
                    WUCBankAccountNo.SelectedValue = ChequeDataSet.Tables(0).Rows(0).Item("BankAccountsID").ToString()
                    rtbChequeNo.Text = ChequeDataSet.Tables(0).Rows(0).Item("ChequeNo").ToString()
                    rdpChequeDate.DbSelectedDate = ChequeDataSet.Tables(0).Rows(0).Item("ChequeDate").ToString()
                    rntbChequeAmount.Text = ChequeDataSet.Tables(0).Rows(0).Item("ChequeAmount").ToString()
                    rtbBeneficiaryName.Text = ChequeDataSet.Tables(0).Rows(0).Item("BeneficiaryName").ToString()
                    rtbBeneficiaryAccountNo.Text = ChequeDataSet.Tables(0).Rows(0).Item("BeneficiaryAccountNo").ToString()
                    rtbBeneficiaryBankName.Text = ChequeDataSet.Tables(0).Rows(0).Item("BeneficiaryBankName").ToString()
                End If
            End If
        End If
    End Sub

    Protected Sub FillVoucherDtl()
        PaymentVoucherHdrDS = PaymentVoucherHdrObj.QueryDatabase(DBParentStoredProcedureClass.SqlQueryType.FillDataset, "RtvPaymentVoucherHdrByID", hdnPaymentVoucherID.Value)
        If PaymentVoucherHdrDS IsNot Nothing Then
            If PaymentVoucherHdrDS.Tables(0).Rows.Count > 0 Then
                rtbYear.Text = PaymentVoucherHdrDS.Tables(0).Rows(0).Item("Year").ToString()
                rtbPaymentVoucherNo.Text = PaymentVoucherHdrDS.Tables(0).Rows(0).Item("PaymentVoucherNo").ToString()
                rdpPaymentVoucherDate.DbSelectedDate = PaymentVoucherHdrDS.Tables(0).Rows(0).Item("PaymentVoucherDate").ToString()
                rcbMainCostCenter.DataBind()
                rcbMainCostCenter.SelectedValue = PaymentVoucherHdrDS.Tables(0).Rows(0).Item("MainCostCenter").ToString()
                rcbCostCenter.DataBind()
                rcbCostCenter.SelectedValue = PaymentVoucherHdrDS.Tables(0).Rows(0).Item("CostCenter").ToString()
                rcbPaidforAccountNo.DataBind()
                rcbPaidforAccountNo.SelectedValue = PaymentVoucherHdrDS.Tables(0).Rows(0).Item("PaidforAccountNo").ToString()
                rtbRemarks.Text = PaymentVoucherHdrDS.Tables(0).Rows(0).Item("Remarks").ToString()
            End If
        End If
    End Sub


    Protected Sub rbtnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles rbtnSave.Click
        Try
            SaveControls()
                RadAjaxManager1.ResponseScripts.Add("radalert('Information Saved Successfully !', 270, 100);")
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Protected Sub rbtnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles rbtnCancel.Click
        Response.Redirect("~/PaymentVoucherHdr.aspx")
    End Sub

    Protected Sub rgPaymentVoucherDtl_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs) Handles rgPaymentVoucherDtl.ItemDataBound
        If (TypeOf e.Item Is GridEditFormItem AndAlso e.Item.IsInEditMode) And _CommandName <> "InitInsert" Then
            'If (TypeOf e.Item Is GridEditFormItem AndAlso e.Item.IsInEditMode) Then

            Dim editFormItem As GridEditFormItem = CType(e.Item, GridEditFormItem)
            Dim parentItem As GridDataItem = editFormItem.ParentItem

            Dim box As RadComboBox = CType(editFormItem.FindControl("WUCAcc").FindControl("rcbv"), RadComboBox)
            box.SelectedValue = parentItem("AccountNo").Text
            Dim box1 As RadComboBox = CType(editFormItem.FindControl("WUCAcc").FindControl("rcbd"), RadComboBox)
            box1.SelectedValue = parentItem("AccountNo").Text

        End If

    End Sub

End Class
